package com.boarsoft.boar.gateway.weixin.common;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.boarsoft.boar.gateway.wechat.common.WechatConfig;

import net.sf.json.JSONObject;

public class AccessToken {

	private Logger log = LoggerFactory.getLogger(AccessToken.class);

	private static String lock = new String();

	private WeixinPlatformUser platformUser;
	private String appId;
	private String secret;
	private long expireTime = 0;
	private String accessToken;
	private boolean isValid = false;

	public boolean isValid() {
		return isValid;
	}

	public void setValid(boolean isValid) {
		this.isValid = isValid;
	}

	public String getAppId() {
		return appId;
	}

	public void setAppId(String appId) {
		this.appId = appId;
	}

	public String getSecret() {
		return secret;
	}

	public void setSecret(String secret) {
		this.secret = secret;
	}

	public AccessToken(WeixinPlatformUser platformUser, String appId, String secret) {
		this.platformUser = platformUser;
		this.appId = appId;
		this.secret = secret;
	}

	public long getCurSecondTime() {
		return System.currentTimeMillis() / 1000;
	}

	public String getAccessToken() throws Exception {
		synchronized (lock) {
			long curSecondTime = getCurSecondTime();
			if (curSecondTime >= expireTime || !isValid) {
				log.info("LianaCore getAccessToken begin.........................");
				// 从共享文件获取
				List<String> last = getLastAccessToken();
				if (last.size() == 2) {
					accessToken = last.get(0);
					expireTime = Long.valueOf(last.get(1));
				}

				if (curSecondTime >= expireTime) {
					JSONObject jsonObject = getNewAccessToken();
					this.accessToken = jsonObject.getString("access_token");
					this.expireTime = curSecondTime + jsonObject.getLong("expires_in") - 300;
					saveAccessToken(accessToken, expireTime);
					isValid = true;
				}
				log.info("LianaCore getAccessToken end appId:" + this.appId + ",token:" + this.accessToken);
			}
			return this.accessToken;
		}
	}

	private void saveAccessToken(String token, long time) {
		try {
			String saveLine = appId + "||" + token + "||" + time;
			String filename = WechatConfig.getProperty("weixin.accessToken.filePath");

			File af = new File(filename);
			if (af.exists()) {

				BufferedReader br = new BufferedReader(new FileReader(new File(filename)));
				String line;
				StringBuffer sb = new StringBuffer();
				while ((line = br.readLine()) != null) {
					if (!line.startsWith(appId))
						sb.append(line).append("\n");
				}
				br.close();
				sb.append(saveLine);
				saveLine = sb.toString();
			}

			BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filename)));
			bw.write(saveLine);
			bw.close();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private List<String> getLastAccessToken() {
		List<String> l = new ArrayList<String>();
		String filename = WechatConfig.getProperty("weixin.accessToken.filePath");
		try {
			BufferedReader br = new BufferedReader(new FileReader(new File(filename)));
			String line;
			while ((line = br.readLine()) != null) {
				if (line.startsWith(appId)) {
					String tmp[] = line.split("\\|\\|");
					String toke = tmp[1];
					String exp = tmp[2];
					l.add(toke);
					l.add(exp);
				}
			}
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return l;
	}

	private JSONObject getNewAccessToken() throws Exception {
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + this.getAppId()
				+ "&secret=" + this.getSecret();
		String resultJson = platformUser.getResult(url);
		JSONObject jsonObject = JSONObject.fromObject(resultJson);
		String accessToken = jsonObject.getString("access_token");
		long expires_in = jsonObject.getLong("expires_in");
		// 需要对返回异常做处理
		return jsonObject;
	}

	public static void main(String args[]) throws Exception {
		String s = "wx8b4df5962f3eaef0||bgnhZOvAIGkgr1DRPA2AyWCjwN9-bDXLGeNs5s75WnUoYBk-KKwzdk3R_lo-nM_AlVDHMCuOjPs05rJa8tu2xg||1419338358";
		String s1 = "ab||cd||ef";
		String si[] = s.split("\\|\\|");
		System.out.println(si[1]);

		AccessToken at = new AccessToken(null, null, null);
		at.getAccessToken();
	}
}
